#ifndef IOFILE_H_HEADER_INCLUDED
#define IOFILE_H_HEADER_INCLUDED

#include "TCHAR.H"

class Writer
{
public:
  virtual ~Writer() {}
  // Write memory chunk into stream/file/whatever
  virtual void write(const void* data, size_t size) = 0;
};

class Writer_File : public Writer
{
public:
  // Construct writer from a FILE* object; void* is used to avoid header dependencies on stdio
  Writer_File(void* file);

  virtual void write(const void* data, size_t size);

private:
  void* file;
};

class Buffered_Writer
{
public:
  // utf8 maximum expansion: x4 (-> utf32)
  // utf16 maximum expansion: x2 (-> utf32)
  // utf32 maximum expansion: x1
  enum {buffcapacity = 2048};

  Buffered_Writer(Writer* writer, int encoding);
  virtual ~Buffered_Writer();

  void flush();
  void flush(LPCTSTR data, size_t size);
  void write(LPCTSTR data);
  void write(LPCTSTR data, size_t length);

private:
  Writer* writer;
  int    encoding;
  TCHAR  buffer[buffcapacity];
  char   scratch[4 * buffcapacity];
  size_t bufsize;
};

class IOFile
{
public:
  int WriteFile(LPCTSTR path, LPCTSTR context);
  LPCTSTR ReadFile(LPCTSTR path);

private:
  void save(Writer_File* writer, int encoding, LPCTSTR context);
  void write(LPCTSTR data, size_t length);

#ifdef _UNICODE_CHARACTER
  char* convert_path_heap(const wchar_t* str);
  FILE* open_file_wide(const wchar_t* path, const wchar_t* mode);
#endif
};

#endif